/**
 * @name v-input 输入框限制
 * @example: <a-input v-input:float /> 正数 最多两位小数
 * @example: <a-input v-input:int /> 自然数
 * @example: <a-input v-input:age /> 年龄 0-150
 * @example: <a-input v-input-blur:float.3 />
 */
export default {
  mounted(el, binding) {
    const input = el.tagName === 'INPUT' ? el : el.querySelector('input')
    el.addEventListener('blur', () => {
      let inputValue = input?.value
      if (binding.arg === 'float') {
        const decimal = Object.keys(binding.modifiers)[0] || 2
        inputValue = parseFloat(inputValue)
        inputValue = inputValue.toFixed(decimal)
      }
      el.value?.length ? (el.value = inputValue) : (el.querySelector('input').value = inputValue)
      trigger(el, 'input')
    })
    const trigger = (el, type) => {
      const e = document.createEvent('HTMLEvents')
      e.initEvent(type, true, true)
      el.dispatchEvent(e)
    }
  }
}
